const path = require('path');
const CompressionWebpackPlugin = require('compression-webpack-plugin');
const UglifyjsWebpackPlugin = require('uglifyjs-webpack-plugin');
// const PrerenderSPAPlugin = require('prerender-spa-plugin');
// const Renderer = PrerenderSPAPlugin.PuppeteerRenderer;
const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin');

const IS_DEV = process.env.NODE_ENV === 'development';

module.exports = {
  publicPath: '/',
  assetsDir: 'static',
  lintOnSave: IS_DEV,
  productionSourceMap: IS_DEV,
  configureWebpack: {
    resolve: {
      alias: {
        '@': path.join(__dirname, 'src'),
        utils: path.join(__dirname, 'src/utils'),
        views: path.join(__dirname, 'src/views'),
        constants: path.join(__dirname, 'src/constants'),
      },
    },
    performance: {
      hints: 'warning',
      maxEntrypointSize: 50000000,
      maxAssetSize: 30000000,
      //只给出 js 文件的性能提示
      assetFilter: function(assetFilename) {
        return assetFilename.endsWith('.js');
      },
    },
    plugins: [
      new SkeletonWebpackPlugin({
        webpackConfig: {
          entry: {
            app: path.join(__dirname, './src/common/entry-skeleton.js'),
          },
        },
        minimize: true,
        quiet: true,
        router: {
          mode: 'history',
          routes: [{ path: '/', skeletonId: 'home' }],
        },
      }),
      //   new PrerenderSPAPlugin({
      //     staticDir: path.join(__dirname, 'dist'),
      //     routes: ['/'],
      //     minify: {
      //       minifyCSS: true, // css压缩
      //       removeComments: true, // 移除注释
      //     },
      //     renderer: new Renderer({
      //       // Optional - The name of the property to add to the window object with the contents of `inject`.
      //       injectProperty: '__PRERENDER_INJECTED',
      //       // Optional - Any values you'd like your app to have access to via `window.injectProperty`.
      //       inject: {},
      //       renderAfterDocumentEvent: 'render-event',
      //     }),
      //   })
    ],
  },
  chainWebpack(config) {
    config.plugins.delete('preload');
    config.plugins.delete('prefetch');

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap((options) => {
        options.compilerOptions.preserveWhitespace = true;
        return options;
      })
      .end();

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(!IS_DEV, (config) => config.devtool('cheap-source-map'));

    if (!IS_DEV) {
      // 开启gzip 但是Nginx上也要做配置
      config
        .plugin('compression')
        .use(CompressionWebpackPlugin)
        .tap(() => [
          {
            filename: '[path].gz[query]',
            algorithm: 'gzip',
            test: /\.js$|\.html$|\.css/, // 匹配文件名
            threshold: 10240, // 超过10k进行压缩
            deleteOriginalAssets: false, // 是否删除源文件
          },
        ]);
      config.optimization.minimizer = [
        new UglifyjsWebpackPlugin({
          // 生产环境推荐关闭 sourcemap 防止源码泄漏
          // 服务端通过前端发送的行列，根据 sourcemap 转为源文件位置
          sourceMap: IS_DEV,
          uglifyOptions: {
            warnings: false,
            compress: {
              drop_console: true,
              drop_debugger: true,
            },
          },
        }),
      ];

      config.optimization.splitChunks({
        chunks: 'all',
        cacheGroups: {
          vendors: {
            name: 'chunk-vendors',
            test: /[\\/]node_modules[\\/]/,
            priority: 10,
            chunks: 'initial', // only package third parties that are initially dependent
          },
          vantUI: {
            name: 'chunk-vantUI', // split vantUI into a single package
            priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
            test: /[\\/]node_modules[\\/]_?vant(.*)/, // in order to adapt to cnpm
          },
        },
      });

      config.module
        .rule('images')
        .use('image-webpack-loader')
        .loader('image-webpack-loader')
        .options({
          bypassOnDebug: true,
        })
        .end();

      config.output.filename('[name].[hash].js').end();
    }
  },
  css: {
    extract: !IS_DEV,
    // extract: true,
    sourceMap: IS_DEV,
    loaderOptions: {
      // ui库主题定制 可在当前引入的less文件处理主题变量
      less: {
        modifyVars: {
          hack: `true; @import "${path.join(__dirname, './src/assets/css/theme.less')}";`,
        },
      },
      postcss: {
        config: {
          path: './postcss.config.js',
        },
      },
    },
  },
  devServer: {
    port: 8089,
    open: true,
    // 开发环境配置代理
    proxy: {
      '/api': {
        target: 'https://api.apiopen.top/',
        changOrigin: true,
        pathRewrite: {
          '^/api': '',
        },
      },
    },
  },
};
